<template>
  <view class="container">
    <CarCard :data="carInfo"></CarCard>

    <!-- 库存表 -->
    <CarSotckTable ref="stockRef" :parentQueryParam="queryParam"></CarSotckTable>
  </view>
</template>

<script setup>
  import { ref, nextTick } from 'vue'
  import { onLoad, onUnload, onPullDownRefresh } from '@dcloudio/uni-app'
  import dayjs from 'dayjs'
  import CarCard from '../components/car-card.vue'
  import CarSotckTable from './index'

  // 查询参数
  const queryParam = ref({
    siteId: undefined,
    modelId: undefined,
    carId: undefined,
    typeList: [],
    startTime: '',
    endTime: '',
  })
  const stockRef = ref([])
  const statistics = ref({})
  // 加载数据
  const loadData = () => {
    nextTick(() => {
      stockRef.value.loadData(queryParam.value, (data) => {
        statistics.value = data
      })
    })
  }

  // 计算结束时间，30天时间
  const calcParamEndtime = (startTime) => {
    const start = dayjs(startTime)
    const min = start.add(30, 'day').subtract(1, 'second')
    return min.format('YYYY-MM-DD HH:mm:ss')
  }

  // 接收参数
  const carInfo = ref()
  onLoad((options) => {
    const data_json = options.data_json || {}
    const data = JSON.parse(data_json)
    data.startDate = dayjs().format('YYYY-MM-DD')
    const now = data.startDate + ' 00:00:00'
    carInfo.value = data
    queryParam.value = {
      siteId: data.siteId,
      modelId: data.modelId,
      carId: data.carId,
      startTime: now,
      endTime: calcParamEndtime(now),
    }
    // 加载数据
    loadData()
  })

  onPullDownRefresh(() => {
    loadData()
  })

  // 排车/改排完成 刷新数据 before
  onLoad(() => {
    uni.$on('carStock:loadData', () => {
      loadData()
    })
  })
  onUnload(() => {
    uni.$off('carStock:loadData')
  })
  // 排车/改排完成 刷新数据 end
</script>

<style lang="less" scoped>
  .lease-time {
    color: #3072f6;
  }
</style>
